package com.example.aidlclientdemo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.aidlservicedemo.ICompute;
import com.example.aidlservicedemo.ILocationService;
import com.example.aidlservicedemo.ISecurityService;

/**
 * BinderPoolActivity 是一个演示如何通过 BinderPool 使用不同服务的 Activity。
 * 它展示了如何连接并使用计算、定位和安全服务，通过 AIDL 实现跨进程通信。
 *
 * @author 猿小蔡
 * @since 2025/6/28
 */
public class BinderPoolActivity extends AppCompatActivity {

    /**
     * 日志标签，用于调试输出。
     */
    private static final String TAG = "MainActivity";

    /**
     * BinderPool 实例，用于获取不同类型的 Binder 服务。
     */
    private BinderPool binderPool;

    /**
     * 显示测试结果的 TextView。
     */
    private TextView resultText;

    /**
     * 启动当前 Activity 的便捷方法。
     *
     * @param context 上下文对象
     */
    public static void start(Context context) {
        Intent starter = new Intent(context, BinderPoolActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binder_pool);
        // 初始化 UI 组件
        resultText = findViewById(R.id.result_text);
        Button computeBtn = findViewById(R.id.compute_btn);
        Button locationBtn = findViewById(R.id.location_btn);
        Button securityBtn = findViewById(R.id.security_btn);
        // 在 IO 线程中初始化 BinderPool
        ThreadPoolManager.ioExecute(() -> {
            binderPool = BinderPool.getInstance(this);
        });
        // 设置按钮点击事件
        computeBtn.setOnClickListener(v -> testComputeService());
        locationBtn.setOnClickListener(v -> testLocationService());
        securityBtn.setOnClickListener(v -> testSecurityService());
    }

    /**
     * 测试计算服务：调用 add 和 multiply 方法，并显示结果。
     */
    private void testComputeService() {
        ThreadPoolManager.ioExecute(() -> {
            try {
                // 获取计算服务的 Binder
                IBinder binder = binderPool.queryBinder(BinderCodes.BINDER_COMPUTE);
                if (binder != null) {
                    ICompute compute = ICompute.Stub.asInterface(binder);
                    int sum = compute.add(5, 7);
                    int product = compute.multiply(3, 4);
                    runOnUiThread(() -> resultText.setText(
                        "Compute Service:\n" + "5 + 7 = " + sum + "\n" + "3 * 4 = " + product));
                } else {
                    Log.w(TAG, "Compute service binder is null");
                }
            } catch (RemoteException e) {
                Log.e(TAG, "Compute service test failed", e);
            }
        });
    }

    /**
     * 测试定位服务：设置模拟位置并获取当前位置信息。
     */
    private void testLocationService() {
        ThreadPoolManager.ioExecute(() -> {
            try {
                // 获取定位服务的 Binder
                IBinder binder = binderPool.queryBinder(BinderCodes.BINDER_LOCATION);
                if (binder != null) {
                    ILocationService locationService = ILocationService.Stub.asInterface(binder);
                    // 设置模拟位置
                    locationService.setMockLocation("40.7128° N, 74.0060° W");
                    // 获取位置
                    String location = locationService.getCurrentLocation();
                    runOnUiThread(() -> resultText.setText(
                        "Location Service:\nCurrent Location: " + location));
                } else {
                    Log.w(TAG, "Location service binder is null");
                }
            } catch (RemoteException e) {
                Log.e(TAG, "Location service test failed", e);
            }
        });
    }

    /**
     * 测试安全服务：加密一段文本，然后解密并展示结果。
     */
    private void testSecurityService() {
        ThreadPoolManager.ioExecute(() -> {
            try {
                // 获取安全服务的 Binder
                IBinder binder = binderPool.queryBinder(BinderCodes.BINDER_SECURITY);
                if (binder != null) {
                    ISecurityService securityService = ISecurityService.Stub.asInterface(binder);
                    String original = "Secret Message 123";
                    String encrypted = securityService.encrypt(original);
                    String decrypted = securityService.decrypt(encrypted);
                    runOnUiThread(() -> resultText.setText(
                        "Security Service:\n" + "Original: " + original + "\n" + "Encrypted: " +
                            encrypted + "\n" + "Decrypted: " + decrypted));
                } else {
                    Log.w(TAG, "Security service binder is null");
                }
            } catch (RemoteException e) {
                Log.e(TAG, "Security service test failed", e);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 断开 Binder 连接池
        if (binderPool != null) {
            binderPool.disconnect();
        }
    }

}